﻿using Frame;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace VideoFileOrganization
{
    public partial class Organizesubdocuments : BaseFrm
    {
        // 在线程中操作 更新界面的委托
        private delegate void IniUiDelegate();

        private bool sameNameAsFolder = false;
        public Organizesubdocuments()
        {
            InitializeComponent();
            this.Text = "子文件夹整理";
            this.Index = 0;
            this.TabImage = Properties.Resources.Organizesubdocuments;
            dgSubDir.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }

        protected override void IniUi()
        {
            UpdataSubDir(RootPath);
        }
        private bool isChecked;
        private string _rootPath;

        private void UpdataSubDir(string rootPath)
        {
            sameNameAsFolder = ckbSameNameAsFolder.Checked;

            dgSubDir.Rows.Clear();
            if (!Directory.Exists(rootPath)) return;
            // 获取目录对象
            DirectoryInfo directory = new DirectoryInfo(rootPath);
            // 获取子文件夹
            DirectoryInfo[] subDirectories = directory.GetDirectories();

            foreach (DirectoryInfo dir in subDirectories)
            {
                // 获取子文件夹
                DirectoryInfo[] subs = dir.GetDirectories();
                // 获取子文件
                string[] subfiles = Directory.GetFiles(dir.FullName);
                //如果没有子文件夹就跳过
                if (subs.Count() <= 0 && rbtnDir.Checked) continue;
                if (subfiles.Count() <= 0 && rbtnFile.Checked) continue;
                dgSubDir.Rows.Add();
                int row = dgSubDir.RowCount - 1;
                dgSubDir.Rows[row].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
                dgSubDir.Rows[row].Cells[0].Value = true;
                //dgSubDir.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                dgSubDir.Rows[row].Cells[1].Value = Path.GetFileName(dir.Name);
                dgSubDir.Rows[row].Cells[2].Value = dir.FullName;
            }
            dgSubDir.Rows.Add();
            int end_row = dgSubDir.RowCount - 1;
            dgSubDir.Rows[end_row].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgSubDir.Rows[end_row].Cells[0].Value = true;
            dgSubDir.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgSubDir.Rows[end_row].Cells[1].Value = "";
            dgSubDir.Rows[end_row].Cells[1].ReadOnly = true;
            dgSubDir.Rows[end_row].Cells[2].Value = "";
            dgSubDir.Rows[end_row].Cells[2].ReadOnly = true;
            panel1.Enabled = true;

            dgSubDir.Columns[0].Width = 35;
        }

        protected override void ApplyButton()
        {
            sameNameAsFolder = ckbSameNameAsFolder.Checked;
            panel1.Enabled = false;
            isChecked = rbtnDir.Checked;
            for (int i = 0; i < dgSubDir.RowCount - 1; i++)
            {
                object cellValue = dgSubDir.Rows[i].Cells[0].Value;
                if (cellValue != null && cellValue.Equals(true))
                {
                    string path = dgSubDir.Rows[i].Cells[2].Value.ToString();
                    ParameterizedThreadStart thread = new ParameterizedThreadStart(OrganizationThread);
                    Thread th = new Thread(thread);
                    th.Start(path);
                    th.Join();
                }
                else
                {
                    continue;
                }
            }
            Invoke(new IniUiDelegate(IniUi));

        }
      
        private void OrganizationThread(Object obj)
        {
            string rootPath = (string)obj;
            
            if (isChecked)
            {
                string[] files = DirectoryHelper.GetSubDirectory(rootPath);
                try
                {
                    foreach (string file in files)
                    {
                        string newPath = DirectoryHelper.Rename(rootPath, file);
                        try
                        {
                            if (File.Exists(newPath))
                            {
                                int count = 1;
                                string originalFileName = Path.GetFileNameWithoutExtension(newPath);
                                string extension = Path.GetExtension(newPath);

                                while (File.Exists(newPath))
                                {
                                    newPath = Path.Combine(rootPath, $"{originalFileName} ({count}){extension}");
                                    count++;
                                }
                            }

                            File.Move(file, newPath);
                        }
                        catch (Exception ex)
                        {
                            SendMsg(newPath + "[" + ex.ToString() + "]", LogLevel.ERROR);
                            return;
                        }
                        string fileRoot = DirectoryHelper.GetRootDirectory(file);
                        int number = Directory.GetFiles(fileRoot).Length;
                        if (number == 0)
                            Directory.Delete(fileRoot);
                    }
                    DirectoryHelper.DeleteEmptyFolders(rootPath);                  
                }
                catch (Exception ex)
                {
                    SendMsg("[" + ex.ToString() + "]", LogLevel.ERROR);
                    return;
                }
            }
            else
            {
                try
                {
                    // 获取当前目录的父目录
                    string parentDirectory = Directory.GetParent(rootPath).FullName;
                    //Debug.Log(_rootPath);
                    if (sameNameAsFolder && DirectoryHelper.HasOnlyOneSubfileAndNoSubfolder(rootPath))
                    {
                        string[] files = Directory.GetFiles(rootPath);
                        string parentDirectoryName = new DirectoryInfo(Path.GetDirectoryName(files[0])).Name;
                        string newFileName = Path.Combine(Path.GetDirectoryName(files[0]), parentDirectoryName + Path.GetExtension(files[0]));
                        try
                        {
                            // 重命名文件
                            File.Move(files[0], newFileName);
                            SendMsg($"文件已重命名为: {newFileName}");
                            rootPath = newFileName;
                        }
                        catch (IOException ex)
                        {
                            SendMsg("文件重命名失败: " + ex.Message);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            SendMsg("没有权限重命名文件: " + ex.Message);
                        }
                    }


                    DirectoryHelper.MoveFiles(rootPath, parentDirectory);
                    //删除空白文件夹
                    DirectoryHelper.DeleteEmptyFolders(parentDirectory);
                }
                catch (Exception ex)
                {
                    SendMsg("[" + ex.ToString() + "]", LogLevel.ERROR);
                    return;
                }
            }
        }

        private void rbtnDir_CheckedChanged(object sender, EventArgs e)
        {
            Invoke(new IniUiDelegate(IniUi));
        }

        private void dgSubDir_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是复选框列
            if (e.ColumnIndex == 0 && e.RowIndex == dgSubDir .Rows.Count - 1)
            {
                // 检查点击的单元格是否是复选框
                if (dgSubDir[e.ColumnIndex, e.RowIndex] is DataGridViewCheckBoxCell)
                {
                    DataGridViewCheckBoxCell cell = dgSubDir[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell;

                    // 切换最后一行的复选框状态
                    cell.Value = !(bool)cell.Value;

                    // 遍历所有行，设置第一列的复选框状态与最后一行相同
                    foreach (DataGridViewRow row in dgSubDir.Rows)
                    {
                        if (row.IsNewRow) continue; // 跳过新增行
                        row.Cells[0].Value = cell.Value;
                    }
                }
            }
        }

        private void dgSubDir_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgSubDir.CurrentRow != null && dgSubDir.CurrentRow.Index >= 0)
            {
                DataGridViewRow selectedRow = dgSubDir.CurrentRow;
                rbtnFile.Checked = true;
                rbtnDir.Checked = false;
                _rootPath = selectedRow.Cells[2].Value?.ToString();
                UpdataSubDir(_rootPath);
            }
        }

        
    }
}
